package com.diploma.project.aiqiyi.exception;

import com.diploma.project.aiqiyi.CommonResponse;
import com.diploma.project.aiqiyi.common.enums.CommonOutputEnum;
import com.diploma.project.aiqiyi.utils.LogUtils;
import com.diploma.project.aiqiyi.utils.RequestUtils;
import com.diploma.project.aiqiyi.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.Set;

@ResponseBody
@ControllerAdvice
@Slf4j
@Order(1)
public class ExceptionHandlerAdvice {

    @ExceptionHandler(Exception.class)
    CommonResponse handleBaseException(HttpServletRequest request, Throwable ex) {
        String uuid = StringUtil.generateUUIDStr();
        String requestId = String.format("[RequestID:%s]", uuid);
        String errorInfo = String.format("[信息码:%s]", uuid.substring(0, 6));

        log.error(LogUtils.getCommLog(String.format("[%s:%s]系统出现未知异常%s:%s", request.getRequestURL().toString(),
                RequestUtils.getRequest4String(request), requestId, ExceptionUtils.getStackTrace(ex))));
        return CommonResponse.fail(CommonOutputEnum.ERROR, errorInfo);
    }

    @ExceptionHandler(BusinessException.class)
    CommonResponse handleBusinessException(HttpServletRequest request, Throwable ex) {
        log.error(ExceptionUtils.getStackTrace(ex));
        BusinessException be = (BusinessException) ex;

        return new CommonResponse(be.getErrorcode(), be.getDescription(), null);
    }

    // JSR303校验失败异常
    @ExceptionHandler(value = ValidationException.class)
    public CommonResponse validationHandle(HttpServletRequest request, ValidationException exception) {
        log.error("ValidationException-->触发JSR303校验: {}", exception.getMessage());
        StringBuffer errorMessage = new StringBuffer();
        if (exception instanceof ConstraintViolationException) {
            ConstraintViolationException exs = (ConstraintViolationException) exception;
            Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
            for (ConstraintViolation<?> item : violations) {
                errorMessage.append("[");
                errorMessage.append(item.getMessage());
                errorMessage.append("] ");
            }
        }
        log.error("参数校验不通过，详细：{}", errorMessage.toString());
        return CommonResponse.fail(4000, "参数校验不通过 :" + errorMessage.toString(), null);
    }
}
